import React, {useCallback, useMemo, useState} from 'react';
import "./style/index.css"
import {Button, Divider, Statistic} from "antd";

/**
 *
 * @param initValue
 * @returns {[unknown,setExpandState]}
 */
const useExpandState =  (initValue)=>{

    const [state, setState] = useState(initValue);

    const setExpandState = (prevState) => {
        setState({
            ...state,
            ...prevState
        });
    }
    return [state,setExpandState];
}


export const CompoundHooksComp = function () {

    const [vote,setVote]=useExpandState({
        up:0,
        down:0
    });

    const count = useMemo(() => {
        let num = 0;

        if (vote.up){
            num+=vote.up;
        }
        if (vote.down){
            num+=vote.down;
        }

        return num;
    }, [vote]);

    const change = useCallback(type=>{
        switch (type) {
            case 'up':
                setVote({up:vote.up+1});
                break;
            case 'down':
                setVote({down:vote.down+1});
                break;
        }
    },[vote])

    return (
        <>
            <div className={'container'}>
                <h2>React是很棒的框架</h2>
                <div>
                    <Statistic title={'人数统计'} num={count} />
                </div>
            </div>
            <Divider/>
            <CompoundHooksMain up={vote.up} down={vote.down}/>
            <CompoundHooksFooter change={change}/>
        </>
    )

};

const CompoundHooksMain = ({up,down})=>{

    return (
        <>
            <div className={'line'}>
                <div>支持人数:
                    {up}
                </div>
            </div>
            <div className={'line'}>
                <div>反对人数:
                    {down}
                </div>
            </div>
        </>
    )
}

const CompoundHooksFooter = React.memo(({change})=>{

    return (
        <>
            <div className={'line'} style={{marginTop:'20px'}}>
                <Button type={'primary'} style={{marginRight:'20px'}} onClick={()=>change('up')}>支持 </Button>

                <Button type={'primary'} danger onClick={()=>change('down')}>反对</Button>
            </div>
        </>
    )
})
;